//
//  XS_MineAssistantsVC.swift
//  XueDao
//
//  Created by Mac on 2020/12/17.
//

import UIKit

public let addImage = UIImage.init(named: "编组-1")!

class XS_MineAssistantsVC: XS_BaseVC {

    @IBOutlet weak var numberLabel: UILabel!
    @IBOutlet weak var textView: QMUITextView!
    @IBOutlet weak var collectionView: UICollectionView!
    
    lazy var imageArray : [UIImage] = [addImage]
    lazy var imageUrlArray : [String] = []
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        view.backgroundColor = #colorLiteral(red: 0.968627451, green: 0.968627451, blue: 0.968627451, alpha: 1)
        title = "意见反馈"
        let rightItem = UIBarButtonItem.init(title: "反馈记录", style: .plain, target: self, action: #selector(feedBackAction))
        rightItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : UIColor.qmui_color(withHexString: "333333")], for: .normal)
        navigationItem.rightBarButtonItem = rightItem
        
        textView.maximumTextLength = 200
        textView.delegate = self
        collectionView.register(UINib.init(nibName: "XS_PickPhotoCell", bundle: Bundle.main), forCellWithReuseIdentifier: "XS_PickPhotoCell")
    }

    @objc func feedBackAction(){
        let feedBackVC = XS_MineFeedBackVC()
        navigationController?.pushViewController(feedBackVC, animated: true)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        view.endEditing(true)
    }

    @IBAction func publishBtnAction(_ sender: UIButton) {
        if textView.text.count == 0 {
            view.makeToast("未填写反馈内容")
            return
        }
//        /opinion/userChat
//        {
//            "content":"发送测试测试测试2",
//            "imgUrl":["http://……………………21","http://……………………22"]
//        }
        //上传图片
        if imageArray.count > 0 {
            for image in imageArray {
                if image.size != addImage.size {
                    let data = image.jpegData(compressionQuality: 0.1)
                    XS_NetWork.xs_uploadFile(XS_NetWork.XS_UploadM(data: data)) { resp in
                        self.imageUrlArray.append(resp?.data ?? "")
                        if self.imageArray.count == 8{
                            if self.imageArray.last?.size == addImage.size {
                                //7张
                                if self.imageUrlArray.count == self.imageArray.count - 1 {
                                    self.commitData()
                                }
                            }else{
                                //8张
                                if self.imageUrlArray.count == self.imageArray.count {
                                    self.commitData()
                                }
                            }
                        }else{
                            if self.imageUrlArray.count == self.imageArray.count - 1 {
                                self.commitData()
                            }
                        }
                    }
                }else{
                    commitData()
                }
            }
        }else{
            commitData()
        }
        
        
    }
    
    func commitData(){
        XS_NetWork.requestJson("/helperChat/userChat",parameters: ["sendContent":textView.text,"imgUrl":imageUrlArray])
            .subscribe(onNext: { resp in //直接返回原始数据 resp.data
                if resp.success{
                    self.view.makeToast("提交成功")
                    self.navigationController?.popViewController(animated: true)
                }else{
                    self.view.makeToast(resp.msg)
                }
            })
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension XS_MineAssistantsVC : UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "XS_PickPhotoCell", for: indexPath) as! XS_PickPhotoCell
        if indexPath.item < imageArray.count {
            cell.image = imageArray[indexPath.item]
        }
        cell.delegate = self
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 15
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 4
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = floor((.screenWidth - 30 - 4 * 3) / 4)
        return CGSize.init(width:  width, height: width)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let image = imageArray[indexPath.item]
        if image.size == addImage.size {
            let picker = TZImagePickerController.init(maxImagesCount: 1, delegate: nil)
            picker?.allowTakeVideo = false
            picker?.allowPickingVideo = false
            picker?.didFinishPickingPhotosHandle = {(photos, assets, isSelectOriginPhoto) in
                if photos?.count ?? 0 > 0 {
                    self.imageArray[indexPath.item] = (photos?.first!)!
                    if self.imageArray.count < 8 {
                        self.imageArray.append(addImage)
                    }
                    self.collectionView.reloadData()
                }
            }
            picker?.modalPresentationStyle = .fullScreen
            present(picker!, animated: true, completion: nil)
        }
    }
    
}

extension XS_MineAssistantsVC : XS_PickPhotoCellDelegate{
    func photoCell(photoCell: XS_PickPhotoCell, didClickDeleteBtn: UIButton) {
        let index = imageArray.firstIndex(of: photoCell.image) ?? 0
        imageArray.remove(at: index)
        if imageArray.count == 0 {
            imageArray.append(addImage)
        }
        collectionView.reloadData()
    }
}

extension XS_MineAssistantsVC : QMUITextViewDelegate{
    func textViewDidChange(_ textView: UITextView) {
        numberLabel.text = String(textView.text.count)+"/200"
    }
    
    func textViewShouldReturn(_ textView: QMUITextView!) -> Bool {
        textView.resignFirstResponder()
        return true
    }
}
